package scau.jump.securitytrace.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.JOptionPane;

import scau.jump.securitytrace.client.ManagerClient;
import scau.jump.securitytrace.dataModel.AddressDataModel;
import scau.jump.securitytrace.init.Init;
import scau.jump.securitytrace.popupwindow.AddressWindow;
import scau.jump.securitytrace.util.AddressConvertUtil;

import com.securitytrace.model.Address;

public class AddAddressButtonListener implements ActionListener {

	private AddressWindow addressWindow;
	
	public AddAddressButtonListener(AddressWindow addressWindow) {
		this.addressWindow = addressWindow;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void actionPerformed(ActionEvent e) {
		String name = addressWindow.getAddressNameTextField().getText();
		ManagerClient managerClient = addressWindow.getManagerClient();
		AddressDataModel addressDataModel = managerClient.getAddressModel();
		
		Vector<Vector<String>> vectors = addressWindow.getAddressModel().getDataVector();
		String desc = AddressConvertUtil.vectorToString(vectors);
		if(name.trim().isEmpty()) {
			JOptionPane.showMessageDialog(addressWindow, "登录信息名称不能为空");
		}else if(desc == null) {
			JOptionPane.showMessageDialog(addressWindow, "登录信息内容不能为空");
		}else {
			Address address = new Address();
			address.setAddressName(name);
			address.setOtherInfo(desc);
			try {
				addAddressToDataBase(address);
				
				int currentPage = addressDataModel.getAddressCurrentPage();
				int pageSize = managerClient.getPageSize();
				int totalPage = 1;
				
				List<Address> addresses = new ArrayList<Address>();
				addresses = Init.getAddressService().getListByPage((currentPage-1) * pageSize, pageSize);
				long addressNumber = Init.getAddressService().getTotalCount();
				if((addressNumber % pageSize) == 0) {
					totalPage = (int) (addressNumber / pageSize);
				}else {
					totalPage = (int) (addressNumber / pageSize) + 1;
				}
				addressDataModel.setDataVector(addresses);
				addressDataModel.setAddressTotal(totalPage);
				managerClient.getAddressPanel().getAddressPageInfoLabel().setText(addressDataModel.getAddressPageInfo());
				addressWindow.dispose();
			} catch(Exception ex) {
				JOptionPane.showMessageDialog(addressWindow, "操作失败");
			}
		}
	}

	private void addAddressToDataBase(Address address) {
		Init.getAddressService().add(address);
		System.out.println("add address");
	}
}
